import dayjs from "dayjs";
import { DateRangeType } from "./timeTool.d";



export * from "./timeTool.d";

/*
	根据当前时间取下一个整点时间
	eg:
	10 : 21 => 10 : 30
	11 : 45 => 12 : 00
	23 : 11 => 23 : 30
	23 : 45 => 00 : 00
*/
const nextHourlyTime = function (tempTime = dayjs(), format = "HH:mm") {
  let time = tempTime;
  let hour = time.hour();
  let minute = time.minute();
  hour = minute > 0 && minute < 30 ? hour : ++hour;
  minute = minute > 0 && minute < 30 ? 30 : 0;
  hour = hour === 23 && minute === 0 ? 0 : hour;
  time = time.hour(hour).minute(minute);
  if (format.length > 0) return time.format(format);
  return time;
};

const testNextHourlyTime = function () {
  const testDatas = [
    {
      hour: 10,
      minute: 21,
      target: "10:30"
    },
    {
      hour: 11,
      minute: 45,
      target: "12:00"
    },
    {
      hour: 23,
      minute: 11,
      target: "23:30"
    },
    {
      hour: 23,
      minute: 45,
      target: "00:00"
    }
  ];
  let num = 0;
  for (let testData of testDatas) {
    let time = dayjs();
    time = time.hour(testData.hour);
    time = time.minute(testData.minute);
    const result = nextHourlyTime(time);
    if (result !== testData.target) {
      console.log("testNextHourlyTime❌: ", testData, "result: ", result);
    } else {
      num++;
    }
  }
  if (num === testDatas.length) {
    console.log("testNextHourlyTime✅");
  }
};

/// 将传入的持续秒数转换为时间 eg： 1小时2分钟18秒
function secondsToDuration(seconds) {
  let hours = Math.floor(seconds / 3600);
  let minutes = Math.floor((seconds % 3600) / 60);
  seconds = seconds % 60;
  let hh = hours > 0 ? hours + "小时" : "";
  let mm = minutes > 0 ? minutes + "分钟" : "";
  let ss = seconds > 0 ? seconds + "秒" : "";
  return hh + mm + ss;
}

function getDateRange(unit: DateRangeType) {
  const now = dayjs();
  const fullYear = now.year();
  const month = now.month();
  const day = now.day();

  // 获取当前日期
  const currentDate = new Date();

  let startDate, endDate;
  switch (unit) {
    case DateRangeType.WEEK: {
      const now = new Date();
      const day = now.getDay() || 7; // 周日为0，转为7
      // 计算本周一
      startDate = new Date(now);
      startDate.setDate(now.getDate() - day + 1);
      break;
    }
    case DateRangeType.MONTH:
      startDate = new Date(fullYear, month, 1);
      break;
    case DateRangeType.QUARTER:
      let startMonth, endMonth;
      if (month < 3) {
        startMonth = 0;
        endMonth = 2;
      } else if (month < 6) {
        startMonth = 3;
        endMonth = 5;
      } else if (month < 9) {
        startMonth = 6;
        endMonth = 8;
      } else {
        startMonth = 9;
        endMonth = 11;
      }
      startDate = new Date(fullYear, startMonth, 1);
      endDate = new Date(fullYear, endMonth + 1, 0);
      break;
    case DateRangeType.YEAR:
      startDate = new Date(fullYear, 0, 1);
      endDate = new Date(fullYear, 11, 31);
      break;

    case DateRangeType.IN_PAST_MONTH: {
      const oneMonthAgo = new Date(currentDate);
      oneMonthAgo.setMonth(currentDate.getMonth() - 1);
      startDate = oneMonthAgo;
      endDate = new Date();
      break;
    }

    case DateRangeType.IN_PAST_QUARTER: {
      const threeMonthsAgo = new Date(currentDate);
      threeMonthsAgo.setMonth(currentDate.getMonth() - 3);
      startDate = threeMonthsAgo;
      endDate = new Date();
      break;
    }

    case DateRangeType.IN_PAST_YEAR: {
      const oneYearAgo = new Date(currentDate);
      oneYearAgo.setFullYear(currentDate.getFullYear() - 1);
      startDate = oneYearAgo;
      endDate = new Date();
      break;
    }

    case DateRangeType.LAST_2_YEARS: {
      const ago2Years = new Date(currentDate);
      ago2Years.setFullYear(currentDate.getFullYear() - 2);
      startDate = ago2Years;
      endDate = new Date();
      break;
    }

    case DateRangeType.LAST_7_YEARS: {
      const ago2Years = new Date(currentDate);
      ago2Years.setFullYear(currentDate.getFullYear() - 7);
      startDate = ago2Years;
      endDate = new Date();
      break;
    }

    case DateRangeType.LAST_7_DAYS: {
      const sevenDaysAgo = new Date(currentDate);
      sevenDaysAgo.setDate(currentDate.getDate() - 6); // 减6天得到近7天（包含今天）
      startDate = sevenDaysAgo;
      endDate = new Date();
      break;
    }

    default:
      return null;
  }
  return {
    startDate: dayjs(startDate).format("YYYY-MM-DD"),
    endDate: dayjs(endDate).format("YYYY-MM-DD")
  };
}

function getDefaultDateRange() {
  return getDateRange(DateRangeType.LAST_7_DAYS);
}

export function getLongTimeAgo() {
  return getDateRange(DateRangeType.LAST_7_YEARS);
}


// 定义枚举
export enum ParameterDateType {
  START_DATE = "START_DATE", // 筛选开始时间
  ENE_DATE = "ENE_DATE", // 筛选结束时间
  ALL = "ALL"
}

// 统一处理为服务器要求的全日期格式
export function formatCompletionTime(time, dateType: ParameterDateType) {
  // 如果已经是"YYYY-MM-DD HH:mm:ss"格式，直接返回
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(time)) {
    return time;
  }
  return time + (dateType === ParameterDateType.ENE_DATE ? " 23:59:59" : " 00:00:00");
}

export const formatDate = function (fdate, format) {
  var date = {
    "Y+": fdate.getFullYear(),
    "M+": fdate.getMonth() + 1,
    "d+": fdate.getDate(),
    "h+": fdate.getHours(),
    "m+": fdate.getMinutes(),
    "s+": fdate.getSeconds(),
    "q+": Math.floor((fdate.getMonth() + 3) / 3),
    "S+": fdate.getMilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(
      RegExp.$1,
      (fdate.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1
          ? date[k]
          : ("00" + date[k]).substr(("" + date[k]).length)
      );
    }
  }
  return format;
};

export const timeAddTS = (startTime, timeStamp, format = "hh:mm:ss") => {
  const a = new Date(startTime).getTime();
  return formatDate(new Date(a + timeStamp), format);
};


export const timeAddTSByFile = (timeStamp, format = "hh:mm:ss") => {
  // 将毫秒转为总秒数
  const totalSeconds = Math.floor(timeStamp / 1000);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  // 格式化输出
  const pad = num => String(num).padStart(2, "0");
  if (hours === 0) {
    // 小时为0时只显示 mm:ss
    return `${pad(minutes)}:${pad(seconds)}`;
  }
  // 否则显示 hh:mm:ss
  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
};

/**
 * 计算两个 "hh:mm:ss" 格式时间字符串的毫秒差
 * @param {string} timeStr1 - 第一个时间字符串
 * @param {string} timeStr2 - 第二个时间字符串
 * @returns {number} 毫秒差（timeStr1 - timeStr2）
 */
export function diffTimeStrToMs(timeStr1, timeStr2) {
  function toMs(str) {
    const [h, m, s] = str.split(":").map(Number);
    return h * 3600000 + m * 60000 + s * 1000;
  }
  return toMs(timeStr1) - toMs(timeStr2);
}

export { secondsToDuration, getDateRange, nextHourlyTime, getDefaultDateRange };
